package entry;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import process.AProcess;

// TODO: get source jars for all libraries
// TODO: save db reconstruction scripts in repository

public abstract class AEntryPoint {

	protected static final String SPRING_CONFIG_FILE = "spring.xml";

	// private final Class<? extends AProcess> processClass;
	private final String processBeanID;

	private ApplicationContext context;

	private int exitCode = 0;

	public AEntryPoint(String processBeanID) {
		this.processBeanID = processBeanID;
	}

	protected void begin() {
		begin(null);
	}

	protected void begin(String args[]) {

		init();

		try {
			process(args);
		} catch (Exception e) {
			exitCode = 1;
			e.printStackTrace();
		} finally {
			finish();
		}
	}

	protected void init() {
		loadSpringContext();
	}

	protected void process(String args[]) {

		AProcess process = (AProcess) context.getBean(processBeanID);

		boolean success = (args == null || args.length == 0) ? process.start()
				: process.start(args);

		if(!success)
			throw new ProcessFailedException();
	}

	protected void finish() {
		System.exit(exitCode);
	}

	protected void loadSpringContext() {
		context = new ClassPathXmlApplicationContext(
				new String[] { SPRING_CONFIG_FILE });
	}
}